package com.ruoyi.framework.security.config;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.config.properties.SecurityConfigProperties;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.dingtalk.DingTalkLoginConfig;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
import com.ruoyi.framework.security.jsonlogin.JsonLoginConfigurer;
import com.ruoyi.framework.security.jsonlogin.JsonLoginProvider;
import com.ruoyi.framework.security.jwt.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.web.authentication.CustWebAuthenticationDetailsSource;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.Filter;

@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityCustomerConfig {

    private DingTalkLoginConfig dingTalkLoginConfig;
    /**
     * 默认的用户信息实现
     */
    private UserDetailsService loginUserDetailService;
    /**
     * 密码最大错误次数
     */
    @Value(value = "${user.password.maxRetryCount:3}")
    private int maxRetryCount;
    /**
     * 密码锁定时间
     */
    @Value(value = "${user.password.lockTime:10}")
    private int lockTime;
    /**
     * 允许匿名访问的地址
     */
    private PermitAllUrlProperties permitAllUrl;
    /**
     * token验证处理
     */
    private TokenService tokenService;
    /**
     * security  参数配置
     */
    private SecurityConfigProperties securityConfigProperties;
    /**
     * json 序列化
     */
    private ObjectMapper objectMapper;
    /**
     * 登录类
     */
    private SysLoginService sysLoginService;
    /**
     * 用户服务层
     */
    private ISysUserService iSysUserService;
    /**
     * redis
     */
    private RedisCache redisCache;

    @Autowired
    public void setDingTalkLoginConfig(DingTalkLoginConfig dingTalkLoginConfig) {
        this.dingTalkLoginConfig = dingTalkLoginConfig;
    }

    @Autowired
    @Qualifier(value = "loginUserDetailServiceImpl")
    public void setLoginUserDetailService(UserDetailsService loginUserDetailService) {
        this.loginUserDetailService = loginUserDetailService;
    }

    @Autowired
    public void setRedisCache(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Autowired
    public void setPermitAllUrl(PermitAllUrlProperties permitAllUrl) {
        this.permitAllUrl = permitAllUrl;
    }

    @Autowired
    public void setSecurityConfigProperties(SecurityConfigProperties securityConfigProperties) {
        this.securityConfigProperties = securityConfigProperties;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setTokenService(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Autowired
    public void setSysLoginService(SysLoginService sysLoginService) {
        this.sysLoginService = sysLoginService;
    }


    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Bean(name = "securityFilterChain")
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(registry -> {
            // 注解标记允许匿名访问的url
            permitAllUrl
                    .getUrls()
                    .forEach(url -> registry.antMatchers(url).permitAll());
            // 对于 验证码captchaImage 允许匿名访问
            registry.antMatchers("/captchaImage").permitAll();
            registry.anyRequest().authenticated();
        });
        // CSRF禁用，因为不使用session
        httpSecurity.csrf(AbstractHttpConfigurer::disable);
        httpSecurity.headers(header -> {
            //   禁用HTTP响应标头
            header.cacheControl().disable();
            //禁用 X-Frame-Options，以允许在页面中嵌入来自其他域的内容（比如 iframe）
            header.frameOptions().disable();
        });
        // 认证失败处理类
        httpSecurity.exceptionHandling(exceptionHand -> {
            exceptionHand.authenticationEntryPoint(new AuthenticationEntryPointImpl());
            exceptionHand.accessDeniedHandler((request, response, accessDeniedException) -> {
                int code = HttpStatus.UNAUTHORIZED;
                String msg = StringUtils.format("请求访问：{}，没有权限，无法访问系统资源", request.getRequestURI());
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
            });
        });
        //禁用http基本认证
        httpSecurity.httpBasic(AbstractHttpConfigurer::disable);
        //禁用表单登录
        httpSecurity.formLogin(FormLoginConfigurer::disable);
        // 基于token，所以不需要session
        httpSecurity.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        // 添加Logout filter
        httpSecurity.logout(logoutConfig -> logoutConfig.logoutUrl("/logout").logoutSuccessHandler(new LogoutSuccessHandlerImpl(tokenService)));
        // 添加JWT filter
        httpSecurity.addFilterBefore(getAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //region json表单登录认证
        //<editor-fold desc="增加表单登录认证器">
        JsonLoginProvider jsonLoginProvider = new JsonLoginProvider(loginUserDetailService, sysLoginService, SecurityUtils.bCryptPasswordEncoder());
        jsonLoginProvider.setVerifyPasswordErrors(true);
        jsonLoginProvider.setRedisCache(redisCache);
        jsonLoginProvider.setLockTime(lockTime);
        jsonLoginProvider.setMaxRetryCount(maxRetryCount);
        httpSecurity.authenticationProvider(jsonLoginProvider);
        //</editor-fold>
        httpSecurity.apply(JsonLoginConfigurer.jsonLogin(jsonLoginConfigurer -> {
            jsonLoginConfigurer.setAuthenticationDetailsSource(new CustWebAuthenticationDetailsSource());
            jsonLoginConfigurer.setSysLoginService(sysLoginService);
            //登录地址
            jsonLoginConfigurer.loginProcessingUrl("/login");
            //成功处理类
            jsonLoginConfigurer.setSuccessHandler((request, response, authentication) -> {
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userDetails.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                iSysUserService.recordLoginInfo(loginUser.getUserId());
                String token = tokenService.createToken(loginUser);
                AjaxResult ajaxResult = AjaxResult.success();
                ajaxResult.put(Constants.TOKEN, token);
                String s = objectMapper.writeValueAsString(ajaxResult);
                ServletUtils.renderString(response, s);
            });
            //失败处理类
            jsonLoginConfigurer.setFailureHandler((request, response, exception) -> {
                String message = exception.getMessage();
                AjaxResult ajaxResult = AjaxResult.error(message);
                ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            });
        }));
        //endregion
        httpSecurity.addFilterBefore(dingTalkLoginConfig.dingTalkLoginAuthenticationFilter(httpSecurity), UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }

    @Autowired
    public void setiSysUserService(ISysUserService iSysUserService) {
        this.iSysUserService = iSysUserService;
    }

    /**
     * token过滤器 验证token有效性
     *
     * @return token过滤器
     */
    private Filter getAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter(tokenService, securityConfigProperties);
    }

    @Bean
    public WebSecurityCustomizer webSecurityFilterChain() throws Exception {
        return web -> {
            // 静态资源，可匿名访问
            web.ignoring().antMatchers(HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**");
            //swagger
            web.ignoring().antMatchers("doc.html", "/swagger-resources/**", "/v3/api-docs/**");
            //druid
            web.ignoring().antMatchers("/druid/**");
        };
    }


}
